const app = getApp()
const i18n = require('../../utils/i18n/index')

Page({
  data: {
    banners: [],
    news: [],
    displayNews: [],
    keyword: '',
    cdnUrl: '',
    locale: 'zh_CN',
    t: {},
    scrollTop: 0,
    isScrolling: false,
    currentIndex: 0
  },

  onLoad() {
    this.setData({
      cdnUrl: app.globalData.cdnUrl
    })
    this.setI18nData()
    this.loadNews()
  },

  onShow() {
    // 开始自动滚动
    //this.startScrolling()
  },

  onHide() {
    // 停止自动滚动
    //this.stopScrolling()
  },

  onUnload() {
    // 停止自动滚动
    //this.stopScrolling()
  },

  startScrolling() {
    this.scrollTimer = setInterval(() => {
      this.scrollNews()
    }, 3000)
  },

  stopScrolling() {
    if (this.scrollTimer) {
      clearInterval(this.scrollTimer)
      this.scrollTimer = null
    }
  },

  scrollNews() {
    const { news, currentIndex } = this.data
    if (news.length <= 5) return

    // 计算下一个索引
    const nextIndex = (currentIndex + 1) % news.length

    // 准备显示的新闻列表（当前5条和下一条）
    const displayNews = []
    for (let i = 0; i < 6; i++) {
      displayNews.push(news[(currentIndex + i) % news.length])
    }

    // 先悄悄把滚动位置重置，这时不需要动画
    this.setData({
      isScrolling: false,
      scrollTop: 0
    })

    // 短暂延迟后开始向上滚动动画
    setTimeout(() => {
      this.setData({
        displayNews,
        isScrolling: true,
        scrollTop: -120
      })

      // 等动画结束后，更新当前索引并重新准备数据
      setTimeout(() => {
        // 移除第一条，在末尾添加新的一条
        displayNews.shift()
        displayNews.push(news[(currentIndex + 6) % news.length])
        
        this.setData({
          currentIndex: nextIndex,
          displayNews,
          isScrolling: false,
          scrollTop: 0
        })
      }, 500)
    }, 50)
  },

  setI18nData() {
    this.setData({
      locale: i18n.getLocale(),
      t: {
        title: i18n.t('index.title'),
        welcome: i18n.t('index.welcome'),
        searchPlaceholder: i18n.t('index.searchPlaceholder'),
        loginRequired: i18n.t('supply.loginRequired'),
        menu: {
          intro: i18n.t('index.menu.intro'),
          alliance: i18n.t('index.menu.alliance'),
          join: i18n.t('index.menu.join')
        },
        newsSection: {
          title: i18n.t('index.newsSection.title')
        }
      }
    })
  },

  onLanguageChange() {
    this.setI18nData()
    this.loadNews()
  },

  // 加载轮播图
  loadBanners() {
    wx.request({
      url: app.globalData.baseUrl + 'banners',
      success: res => {
        if (res.data.code === 0) {
          this.setData({
            banners: res.data.data || []
          })
        }
      }
    })
  },

  // 加载新闻
  loadNews() {
    wx.request({
      url: app.globalData.baseUrl + 'public/home',
      success: res => {
        if (res.data.code === 0) {
          const news = res.data.data.needs || []
          // 准备初始显示的6条新闻（5条显示+1条用于滚动）
          const displayNews = news.slice(0, 6)
          this.setData({
            news: news.slice(0, 10),
            displayNews,
            banners: res.data.data.banners || []
          })
        }
      }
    })
  },

  // 搜索处理
  onSearch(e) {
    const keyword = e.detail.value
    wx.setStorageSync('searchKeyword', keyword)
    wx.switchTab({
        url: '/pages/supply/supply'
    })
  },

  // 菜单项点击
  onMenuTap(e) {
    const { type } = e.currentTarget.dataset
    switch (type) {
      case 'intro':
        wx.navigateTo({
          url: '/pages/intro/intro?id=1'
        })
        break
      case 'alliance':
        wx.navigateTo({
          url: '/pages/intro/intro?id=2'
        })
        break
      case 'join':
        wx.navigateTo({
          url: '/pages/mine/join/join'
        })
        break
    }
  },

    // banner点击
    onBannerTap(e) {
        const { type,a_id,id } = e.currentTarget.dataset
        console.log(type)
        if (type == 0) {
            wx.navigateTo({
                url: `/pages/banner/banner?id=${id}`
              })
        }else if(type == 1) {
            wx.navigateTo({
                url: `/pages/supply/detail/detail?id=${a_id}`
              })
        } else if(type == 2) {
            if (!app.globalData.isLogin) {
                wx.showModal({
                  title: i18n.t('common.confirm'),
                  content: this.data.t.loginRequired,
                  confirmText: i18n.t('mine.login'),
                  success: function(res) {
                    if (res.confirm) {
                      wx.navigateTo({
                        url: '/pages/mine/login/login'
                      })
                    }
                  }
                })
                return
            }
            wx.navigateTo({
                url: '/pages/supply/publish/publish'
              })
        }
        
      },
      
  // 新闻点击
  onNewsTap(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/supply/detail/detail?id=${id}`
    })
  },

  // 切换语言
  onSwitchLang() {
    const newLocale = this.data.locale === 'zh_CN' ? 'en_US' : 'zh_CN'
    i18n.setLocale(newLocale)
    this.setI18nData()
    this.loadNews()
  }
}) 